<template>
  <div class="page">
    <div class="index">
      <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options1"
        @select="onSelect"
      />
      <div class="swiper">
        <van-swipe
          @change="onChange"
          class="my-swipe"
          :autoplay="3000"
          indicator-color="white"
          ref="swipeTo"
          placement="bottom"
        >
          <van-swipe-item>
            <img :src="goods.img1" />
          </van-swipe-item>
          <van-swipe-item>
            <img :src="goods.img2" />
          </van-swipe-item>
          <van-swipe-item>
            <img :src="goods.img3" />
          </van-swipe-item>
          <van-swipe-item>
            <img :src="goods.img4" />
          </van-swipe-item>
          <template #indicator>
            <div class="custom-indicator">{{ current + 1 }}/4</div>
          </template>
        </van-swipe>
        <van-sticky>
          <div class="fh"><van-icon name="arrow-left" @click="fh" /></div>
          <van-popover
            v-model="showPopover"
            trigger="click"
            :actions="actions"
            class="more"
            style="font-size: 30px"
            theme="dark"
            @select="onSelect"
          >
            <template #reference>
              <van-icon name="ellipsis" style="slh" />
            </template>
          </van-popover>
        </van-sticky>
      </div>
      <div class="detail">
        <div class="dtop">
          <span class="money">￥{{ goods.originprice }}</span>
          <span class="sales">销量:{{ goods.sales }}</span>
        </div>
        <div class="dmodel">
          <span class="brand">{{ goods.brand }}</span>
          <span class="category">{{ goods.category }}</span>
          <span class="proname">{{ goods.proname }}</span>
        </div>

        <div class="dbottom">
          <van-field
            v-model="fieldValue"
            is-link
            readonly
            label="地区"
            placeholder="请选择所在地区"
            @click="show = true"
            class="dq"
          />
          <van-popup v-model="show" round position="bottom">
            <van-cascader
              v-model="cascaderValue"
              title="请选择所在地区"
              :options="options"
              @close="show = false"
              @finish="onFinish"
            />
          </van-popup>
        </div>
        <div class="guessLike">
          <span>猜你喜欢</span>
          <van-list
            class="list"
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            offset="0"
          >
            <div
              v-for="item in list"
              :key="item.proid"
              class="sp"
              @click="render(item.proid)"
            >
              <img :src="item.img1" />
              <p class="title">{{ item.proname }}</p>
              <p class="price">￥{{ item.originprice }}</p>
            </div>
          </van-list>
        </div>
      </div>
    </div>
    <div class="btm">
      <van-goods-action>
        <van-goods-action-icon icon="chat-o" text="客服" />
        <van-goods-action-icon icon="cart-o" text="购物车" @click="gwc" />
        <van-goods-action-icon
          icon="star"
          :text="text ? '收藏' : '已收藏'"
          :color="color ? '' : '#ff5000'"
          @click="sc"
        />
        <van-goods-action-button
          type="warning"
          text="加入购物车"
          @click="addGoods"
        />
        <van-goods-action-button type="danger" text="立即购买" />
      </van-goods-action>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import axios from "axios";
export default {
  name: "DetailVue",
  data() {
    return {
      goods: [],
      comments: [],
      urls: [],
      current: 0,
      showPopover: false,
      show: false,
      fieldValue: "",
      cascaderValue: "",
      list: [],
      loading: false,
      finished: false,
      showShare: false,
      pageIndex: 1,
      options1: [
        { name: "微信", icon: "wechat" },
        { name: "微博", icon: "weibo" },
        { name: "复制链接", icon: "link" },
        { name: "分享海报", icon: "poster" },
        { name: "二维码", icon: "qrcode" },
      ],
      // 选项列表，children 代表子选项，支持多级嵌套
      options: [
        {
          text: "浙江省",
          value: "330000",
          children: [{ text: "杭州市", value: "330100" }],
        },
        {
          text: "江苏省",
          value: "320000",
          children: [{ text: "南京市", value: "320100" }],
        },
      ],
      text: "true",
      color: "true",
      showPopover: false,
      actions: [
        { text: "首页", icon: "home-o" },
        { text: "我的", icon: "user-circle-o" },
        { text: "分享", icon: "share-o" },
      ],
    };
  },
  created() {
    
    let goodsId = this.$route.params.id;
    // console.log('goodsId: ', goodsId);
    this.$service
      .get("/api/pro/detail/" + goodsId)
      .then((res) => {
        if (res.data.code == 200) {
          // console.log("res.data.data", res.data.data);
          this.goods = res.data.data;
          // console.log("goods: ", this.goods);
        }
      })
      .catch((err) => {
        console.log(err, "err");
      });
  },
  //组件内部钩子
  //beforeRouterEnter（to，from，next）：不能获取组件实例this,created之前
  //beforeRouterUpdate（to，from，next）：当前路径发生改变
  //beforeRouterLeave（to，from，next）：导航离开该组件时调用
  beforeRouteUpdate(to, from, next) { //检测路由的变化
    console.log(to);
    this.$service({ url: "/api/pro/detail/" + to.params.id })
      .then((res) => {
        // console.log(res.data);
        if (res.data.code == 200) {
          // console.log("res.data.data", res.data.data);
          this.goods = res.data.data;
          // console.log("goods: ", this.goods);
        }
      })
    next();
  },
  methods: {
    onChange(index) {
      this.current = index;
    },
    fh() {
      this.$router.go(-1);
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({ selectedOptions }) {
      this.show = false;
      this.fieldValue = selectedOptions.map((option) => option.text).join("/");
    },

    sc() {
      this.text = !this.text;
      this.color = !this.color;
    },
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      axios({
        url: "/api/pro/list",
        params: {
          count: this.pageIndex,
          limitNum: 10,
        },
      })
        .then((res) => {
          if (res.data.code == 200) {
            this.list = [...this.list, ...res.data.data];
            // console.log("res.data.date", res.data.data);
            this.loading = false;
            this.pageIndex++;
          }
        })
        .catch((err) => {
          // console.log(err, "err");
        });
    },
    render(id) {
      this.$router.push("/DetailVue/" + id);
      // this.$service
      //   .get("/api/pro/detail/" + id)
      //   .then((res) => {
      //     if (res.data.code == 200) {
      //       // console.log("res.data.data", res.data.data);
      //       this.goods = res.data.data;
      //       // console.log("goods: ", this.goods);
      //     }
      //   })
      //   .catch((err) => {
      //     console.log(err, "err");
      //   });
    },
    onSelect(action) {
      if (action.text == "首页") {
        this.$router.replace({ path: "/Home" });
      }
      if (action.text == "我的") {
        this.$router.replace({ path: "/Mine" });
      }
      if (action.text == "分享") {
        // this.$router.replace({ path: "/Mine" });
        this.showShare = true;
      }
    },
    gwc() {
      this.$router.push({ path: "/GoodsCart" });
    },
    addGoods() {
      let token = localStorage.getItem("token");
      console.log("token: ", token);
      let userid = localStorage.getItem("userid");
      let goodsId = this.$route.params.id;
      console.log(goodsId);
      this.$service({
        method: "post",
        url: "/api/cart/add",
        headers: { token },
        data: {
          userid,
          proid: goodsId,
          num: 1,
        },
      })
        .then((res) => {
          // console.log(res, "res");
          if (res.data.code == 10119) {
            Toast("加入购物车成功");
            this.$router.push("/Login");
          }
        })
        .catch((err) => {
          console.log(err, "err");
        });
    },
  },
};
</script>

<style scoped>
.page {
  height: 100%;
  width: 100%;
  /* box-sizing: border-box; */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.index {
  flex: 1;
  overflow: auto;
  /*  display: flex;
  flex-direction:column ; */
}
.slh {
  height: 20px;
  width: 20px;
  display: block;
}
.dq {
  height: 50px;
  line-height: 30px;
}
.btm {
  height: 2.5rem;
  background-color: #000;
}
.guessLike {
  font-weight: 700;
  font-size: 14px;
  width: 100%;
  overflow: hidden;
}
.swiper {
  position: relative;
}
.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
  text-align: center;
}
.custom-indicator {
  position: absolute;
  right: 0px;
  bottom: 4rem;
  background-color: rgba(128, 128, 128, 0.476);
  width: 3rem;
  text-align: center;
  border-radius: 10px 0 0 10px;
}
.swiper img {
  width: 100%;
  height: 90%;
}
.fh {
  position: fixed;
  font-size: 30px;
  left: 1rem;
  top: 10px;
}
.more {
  position: fixed;
  width: 30px;
  right: 3.5rem;
  top: 10px;
}
.detail {
  height: 5rem;
  margin-top: -13px;
}
.dtop {
  display: flex;
  justify-content: space-between;
}
.sales {
  font-size: 10px;
  margin-top: 10px;
  margin-right: 10px;
}
.money {
  font-size: 25px;
  margin-left: 10px;
  color: red;
}
.dmodel {
  font-size: 14px;
  margin-left: 0.25rem;
  margin-right: 0.25rem;
}
.brand {
  color: white;
  background-color: red;
  display: inline-block;
  /* width: 45px; */
  text-align: center;
  font-weight: 300;
  font-size: 12px;
}
.category {
  color: white;
  background-color: rgba(0, 34, 255, 0.774);
  display: inline-block;
  /* width: 45px; */
  text-align: center;
  margin-left: 0.25rem;
  margin-right: 0.25rem;
  font-weight: 300;
  font-size: 12px;
}
.proname {
  font-weight: 700;
}
.dbottom {
  border-top: 8px solid rgba(128, 128, 128, 0.289);
  border-bottom: 8px solid rgba(128, 128, 128, 0.289);
}
.list {
  width: 100%;
  column-count: 2;
  font-size: 0.875rem;
  background-color: #ededed;
  column-gap: 0.3125rem;
}
.list .sp {
  width: 100%;
  text-align: center;
  background-color: white;
  border-radius: 0.625rem;
  break-inside: avoid;
  margin-bottom: 0.625rem;
}
.list .sp img {
  border-radius: 0.5rem;
  width: 90%;
  margin-top: 0.625rem;
}
.list .sp .title {
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin: 0.625rem 0;
}
.list .sp .price {
  text-align: left;
  color: orange;
  font-size: 1.125rem;
}
</style>